//
//  MyView.m
//  UIBezierPath
//
//  Created by qianfeng007 on 15/8/6.
//  Copyright (c) 2015年 李金柱. All rights reserved.
//

#import "MyView.h"

@implementation MyView
{
    UIBezierPath *_bezierPath;

}
-(instancetype)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        [self createButtons];
  
    }
    
    
    return self;
}
- (void)createButtons {
    NSArray *titles = @[@"clear"];
    for (NSInteger i = 0; i < titles.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(250, 100+30*i, 100, 30);
        button.tag = 101+i;
        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
    //实例化一个 贝塞尔路径(画笔)
    _bezierPath = [UIBezierPath bezierPath];
}
- (void)btnClick:(UIButton *)button {
    //把所有的点 删除
    [_bezierPath removeAllPoints];
    //重新渲染 self视图
    [self setNeedsDisplay];
}

#pragma mark - 手指开始触摸屏幕

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //获取开始触摸的点
    UITouch *myTouch = [touches anyObject];
    CGPoint point = [myTouch locationInView:self];
    //把画笔移动触摸的点
    [_bezierPath moveToPoint:point];
}
//手指 在屏幕上移动
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    //获取触摸
    UITouch *myTouch = [touches anyObject];
    //触摸的点
    CGPoint point = [myTouch locationInView:self];
    //把 路径上的前一个点和当前点进行连线
    [_bezierPath addLineToPoint:point];
    //根据描述的路径 重新绘图(重新渲染)
    [self setNeedsDisplay];
}
/*
 当我们要想重新渲染视图(绘图)需要手动调用下面的方法
 - setNeedsDisplay
 - (void)setNeedsDisplayInRect:(CGRect)rect;
 
 //这两个方法会自动调用 - (void)drawRect:(CGRect)rect
 
 - (void)drawRect:(CGRect)rect我们不能手动调用 否则会出问题
 //我们绘制路径重新绘图的操作 放在 - (void)drawRect:(CGRect)rect中
 
 //视图第一次加载的时候就要渲染 自动调用- (void)drawRect:(CGRect)rect
 */


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
//根据路径 重新对当前视图 进行自定义绘图
- (void)drawRect:(CGRect)rect {
    // Drawing code
    NSLog(@"- drawRect");
    
    //设置线条的宽
    _bezierPath.lineWidth = 5;
    //设置颜色
    [[UIColor redColor] set];//设置了线条的颜色和填充的颜色
    
    //告知系统 进行沿着绘图路径进行绘图
    [_bezierPath stroke];//提交笔画(路径) 绘图
}

@end
